<template>
  <div class="main-table-content">

    <!--搜索栏-->
    <!--    <el-form class="search-form" ref="searchFormRef" :model="searchForm" :inline="true" label-width="70">-->

    <!--      <el-form-item label="标题内容" prop="title">-->
    <!--        <el-input v-model="searchForm.title" placeholder="请输入" clearable style="width: 200px"-->
    <!--                  @keyup.enter="searchData"/>-->
    <!--      </el-form-item>-->

    <!--      <el-form-item label="通知类型" prop="type">-->
    <!--        <el-select v-model="searchForm.type" placeholder="请选择" clearable style="width: 130px">-->
    <!--          <el-option v-for="dict in enu_sys_msg_read_type" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
    <!--        </el-select>-->
    <!--      </el-form-item>-->

    <!--      <el-form-item label="阅读状态" prop="isRead">-->
    <!--        <el-select v-model="searchForm.isRead" placeholder="请选择" clearable style="width: 100px">-->
    <!--          <el-option v-for="dict in enu_sys_msg_read" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
    <!--        </el-select>-->
    <!--      </el-form-item>-->

    <!--      <el-form-item>-->
    <!--        <el-button type="primary" icon="Search" @click="searchData">搜索</el-button>-->
    <!--        <el-button icon="Refresh" @click="resetSearch">重置</el-button>-->
    <!--      </el-form-item>-->

    <!--    </el-form>-->

    <!--按钮组-->
    <div class="fx mgb12">
      <el-button plain :color="'#7a81ea'" size="small" icon="Finished" @click="readBatch">批量已读</el-button>
      <el-button plain :color="'#afa262'" size="small" icon="Sunset" @click="readAll">全部已读</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="deleteBatch">批量删除</el-button>
      <div class="fx1"></div>
      <el-button type="primary" icon="Refresh" @click="searchData">刷新</el-button>
    </div>
    <!--表格-->
    <el-table
        highlight-current-row
        style="border: 1px solid #E1E6EB"
        :header-cell-style="{background:'#F5F6FA'}"
        row-key="id" v-loading="option.loading"
        :data="option.tableData"
        @selection-change="selectionChange">

      <el-table-column type="selection" width="55"/>
      <el-table-column label="标题内容" prop="title" align="center" :show-overflow-tooltip="true" width="150">
        <template #default="scope">
          <el-tag>{{ scope.row.title }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="消息内容" prop="content"></el-table-column>
      <el-table-column label="通知时间" prop="ct" align="center" width="200"></el-table-column>
      <el-table-column label="通知类型" prop="msgTypeName" :show-overflow-tooltip="true"
                       align="center" width="200">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.msgTypeName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="阅读状态" prop="isRead" :show-overflow-tooltip="true"
                       align="center" width="100">
        <template #default="scope">
          <dict-tag :options="enu_sys_msg_read" :value="scope.row.isRead"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="read(scope.row)">
            已读
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="fxEnd">
      <el-pagination
          class="mgt8"
          small
          background
          :total="option.totalRow"
          :page-sizes="option.pageSizes"
          v-model:current-page="searchForm.pageNumber"
          v-model:page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="searchData"
          @current-change="searchData"
      />
    </div>

  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import {apiAllMyCreateRole, apiSysMsgDelete, apiSysMsgReadAll, apiSysMsgReadBatch, apiSysMsgUserPageData} from "@/api/system";
import $modal from "@/common/utils/modal";
import {copyNew} from "@/common/utils/kit";
import {asDict} from "@/api/common";
import DictTag from "@/common/component/DictTag.vue";
import {useRouter} from "vue-router";
import $event from "@/common/utils/event";

const {proxy} = getCurrentInstance();
const router = useRouter()

const {
  enu_sys_msg_read,
  enu_sys_msg_read_type,//系统通知-通知类型
  enu_sys_msg_read_range,//系统通知-通知范围
  enu_sys_msg_read_limit,//系统通知-接收条件
} = asDict("enu_sys_msg_read", "enu_sys_msg_read_type", "enu_sys_msg_read_range", "enu_sys_msg_read_limit");

let optionKey = {
  loading: false,
  dialogType: "",
  dialogTitle: "",
  openDialog: false,
  tableData: [],
  selectIds: [],
  selectNames: [],
  pageSizes: [1, 10, 20, 50, 100],
  totalRow: 0,
  nowRoleId: 0,
  defaultChecked: [],
  allRole: [],
}
let formKey = {
  title: "",
  content: "",
  type: "0",
  readRange: "0",
  readLimit: "0",
}
let searchKey = {
  pageNumber: 1,
  pageSize: 10,
  // 相关搜索参数
  title: "",
  content: "",
  searchRange: "0",
  readRange: "",
  readLimit: "",
}

const formRules = ref({
  title: [{required: true, message: "不能为空", trigger: "blur"}],
  content: [{required: true, message: "不能为空", trigger: "blur"}],
  type: [{required: true, message: "不能为空", trigger: "change"}],
  readRange: [{required: true, message: "不能为空", trigger: "change"}],
  readLimit: [{required: true, message: "不能为空", trigger: "change"}],
  roleIds: [{required: true, message: "不能为空", trigger: "blur"}],
  userIds: [{required: true, message: "不能为空", trigger: "blur"}],
});

const searchForm = ref(searchKey)
const formData = ref(formKey);
const option = ref(optionKey);


function resetForm() {
  formData.value = copyNew(formKey);
}

function resetSearch() {
  proxy.$refs["searchFormRef"].resetFields();
}


$event.on("searchMsg", (res) => {
  searchData()
})

watch(() => router.currentRoute.value.path, (toPath) => {
  if (toPath === '/sys/sysMsgList') {
    searchData()
  }
}, {immediate: true, deep: true})

//页面加载完成回调
onMounted(() => {
  searchData()

  apiAllMyCreateRole().then(res => {
    option.value.allRole = res.data
  })

})


function selectionChange(rows) {
  option.value.selectIds = rows.map(item => item.id);
  option.value.selectNames = rows.map(item => item.title);
}

//搜索数据
function searchData() {
  option.value.loading = true;
  setTimeout(() => {
    apiSysMsgUserPageData(searchForm.value).then(res => {
      let {totalRow, records, pageNumber, pageSize} = res.data;
      option.value.loading = false;
      option.value.totalRow = totalRow * 1
      option.value.tableData = records
      searchForm.value.pageNumber = pageNumber * 1
      searchForm.value.pageSize = pageSize * 1
    })
  }, 500)

}

function deleteBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }

  //console.log(ids)
  let content = `正在删除名称为【 ${option.value.selectNames.join("、")}】 的数据项，是否确定删除？ `
  $modal.confirmWarning(content)
      .then(async () => {
        apiSysMsgDelete({ids: option.value.selectIds.join(",")}).then(res => {
          if (res.success) {
            $modal.success();
            $event.emit("searchMsg", {})
          }
        })
      }).catch(() => $modal.cancel());
}

function read(row) {
  apiSysMsgReadBatch({msgIds: row.id}).then(res => {
    if (res.success) {
      $modal.success();
      $event.emit("searchMsg", {})
    }
  })
}

function readAll() {
  let content = `所有消息全部已读，是否继续操作？`
  $modal.confirmWarning(content).then(() => {
    apiSysMsgReadAll().then(res => {
      if (res.success) {
        $modal.success();
        $event.emit("searchMsg", {})
      }
    })
  }).catch(() => {
  })
  $event.emit("searchMsg", {})
}

function readBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  //console.log(ids)
  let content = `批量已读标题为【 ${option.value.selectNames.join("、")}】 的数据项，是否继续？ `
  $modal.confirmWarning(content)
      .then(async () => {
        apiSysMsgReadBatch({msgIds: option.value.selectIds.join(",")}).then(res => {
          if (res.success) {
            $modal.success();
            $event.emit("searchMsg", {})
          }
        })
      }).catch(() => $modal.cancel());

}

</script>

<style scoped lang="less">
</style>